//
//  JCOAuthViewController.swift
//  SinaWeibo_18
//
//  Created by mac on 15/10/12.
//  Copyright © 2015年 cz. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class JCOAuthViewController: UIViewController, UIWebViewDelegate {

    let App_Key = "3636479371"
    let App_Secret = "2b597750084d21ba06c2aec388201a35"
    let redirect_uri = "http://baidu.com"
    
    var webView: UIWebView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNav()
        //设置用户登录界面
        let webView = UIWebView(frame: UIScreen.mainScreen().bounds)
        //设置代理
        webView.delegate = self
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(App_Key)&redirect_uri=\(redirect_uri)")
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        view.addSubview(webView)
        self.webView = webView
    }

    private func setupNav(){
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
    }
    //15656514046  z920618
    @objc private func autoFill(){
        let script = "document.getElementById('userId').value = '15656514046';document.getElementById('passwd').value = 'z920618'"
        self.webView?.stringByEvaluatingJavaScriptFromString(script)
    }
    
    // MARK: - webViewDelegate
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL?.absoluteString
        if urlString!.hasPrefix(redirect_uri) {
            printLog("回调地址:\(urlString)")
            //判断是否有code
            let codePre = "code="
            let range = (urlString! as NSString).rangeOfString(codePre)
            if range.location != NSNotFound {
                let code = (urlString! as NSString).substringFromIndex(range.location + range.length)
                printLog("code = \(code)")
                
                //请求访问令牌
                loadAccessToken(code)
                //不继续加载网页
                return false
                
//                return true
            }
        }
        return true
    }
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    //获取 accessToken
    private func loadAccessToken(code: String){
        let manager = AFHTTPSessionManager()
        //给序列化器添加内容类型
        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = [
            "client_id": App_Key,
            "client_secret": App_Secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        manager.POST(urlString, parameters: params, success: { (datatask, result) -> Void in
            printLog("请求成功\(result)")
            //返回的accessToken数据
                //字典转模型
           if let res = (result as? [String: AnyObject]){
                let account = JCUserAccount(dict: res)
//            printLog("account:\(account)")
//            //保存账户信息
//            account.saveUserAccount()
            
            //通过 访问令牌 获取用户信息
            self.loadUserInfo(account)
            
                        }
            
            }) { (datatask, error) -> Void in
                SVProgressHUD.dismiss()
                printLog("请求失败\(error)")
        }
    }
    //获取 个人信息
    private func loadUserInfo(account:JCUserAccount){
        printLog("loadUserInfo")
        //请求地址
        let urlString = "https://api.weibo.com/2/users/show.json"
        //参数
        let params = [
            "access_token":account.access_token!,
            "uid":account.uid!
        ]
        let manager = AFHTTPSessionManager()
        //get请求
        manager.GET(urlString, parameters: params, success: { (dataTask, result) -> Void in
            
            //获取用户头像 和 昵称
            account.avatar_large = result["avatar_large"] as? String
            account.screen_name = result["screen_name"] as? String
            
            //获取后再保存
            printLog("account:\(account)")
            account.saveUserAccount()
            
            SVProgressHUD.dismiss()
            //在得到头像地址后跳转
            //跳转界面
           let window = UIApplication.sharedApplication().delegate!.window!
            window?.rootViewController = JCWecomeViewController()

            
            }) { (dataTask, error) -> Void in
                SVProgressHUD.dismiss()
        }
    }
    


}
